package com;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class PruebaJavassist {
	
	private ClassPool source;
	
	private List<String> metodosALogear;
	
	public PruebaJavassist() {
		source = ClassPool.getDefault();
		try {
			source.insertClassPath("C:\\Documents and Settings\\Cristian\\Mis documentos\\" +
					"workspace-trabajoprofesional\\AplicationExample\\target\\classes");
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		metodosALogear = new LinkedList<String>();
	}

	public void aspectearClase(String nombreClase) throws NotFoundException, CannotCompileException {
		CtClass ctClass = source.get(nombreClase);
		CtMethod[] metodos = ctClass.getMethods();
		for(CtMethod metodo:metodos) {
			if(logeoMetodo(metodo.getName())) {
				metodo.insertBefore("{System.out.println(\"Ejecutandose el metodo " + metodo.getName() + "\");}");
			}
		}
		
		DataOutputStream stream = null;
		
		try {
			stream = new DataOutputStream(new FileOutputStream(new File("C:\\Documents and Settings\\Cristian\\Mis documentos\\" +
					"workspace-trabajoprofesional\\AplicationExample\\target\\classes\\aplication\\Point.class")));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		try {
			stream.write(ctClass.toBytecode());
			stream.flush();
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void logearMetodo(String nombre) {
		this.metodosALogear.add(nombre);
	}

	private boolean logeoMetodo(String name) {
		return metodosALogear.contains(name);
	}
}
